import { Form } from '@ant-design/compatible';
import AuthComponent from '@/components/Authorized/AuthComponent';
import '@ant-design/compatible/assets/index.css';
import { DatePicker, message, Input, Select, Button } from 'antd';
import router from 'umi/router'
import React, { useState, useCallback, useRef, useEffect } from 'react';
import ProTable from '@ant-design/pro-table';
import { useRequest } from '@umijs/hooks';
import { connect } from 'dva';
import { queryFlightTable, queryCityInfo } from './service';
import moment from 'moment';
import styles from './index.less';
const { Option } = Select;

// 设置时间
const nowTimeStamp = Date.now();
const now = new Date(nowTimeStamp);
const TableList = (props) => {
  const { data: selectData } = useRequest(queryCityInfo,{loadingDelay: true}); //获取出发和到达航站
  const [height, controlH] = useState(300); // 设置表格的高度
  const [isCollapse, controlC] = useState(true); //搜索面板是否折叠
  const [selectRow, setSelectRow] = useState([])// 选中的项
  const [selectedRowKeys, setSelectedRowKeys] = useState([])// 选中项的id
  // 计算表格高度
  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 360);
    } else {
      controlH(document.body.clientHeight - 470);
    }
  }, [isCollapse]);

  const actionRef = useRef();
  const ref = useRef();
  const [flightId, setflightId] = useState('0');//航班id

  const [_startDate, setStartDate] = useState(now)
  const [_endDate, setEndDate] = useState(now)

  
  //航班号
  const formatFlightNo = (val) => {
    if (!val) {
      return '';
    } else if (val.length < 3 || /^\D/.test(val)) {
      return ''.toUpperCase.call(val);
    } else if (/^\d{2}/.test(val)) {
      return `3U${val}`;
    } else {
      return val;
    }
  }
  // 切换清空搜索
  useEffect(() => {
    // 解除dva中的数据缓存
    props.dispatch({
      type: 'auditDetail/resetUploadList'
    });
  }, [])

  // 搜索前的回调
  const beforeSearchSubmit = useCallback(params => {

    params['beginFlightDate'] = params.beginFlightDate ? params.beginFlightDate.format('YYYY-MM-DD') : '';
    params['endFlightDate'] = params.endFlightDate ? params.endFlightDate.format('YYYY-MM-DD') : '';

    if (!isCollapse) {
      return { ...params }
    } else {
      if (event.target.querySelector('span') && event.target.querySelector('span').innerText === '查 询') {
        if (Object.keys(params).indexOf('beginFlightDate') === -1) {
          params.beginFlightDate = ''
        }
        if (Object.keys(params).indexOf('endFlightDate') === -1) {
          params.endFlightDate = ''
        }
      } else if (event.target.querySelector('span') && event.target.querySelector('span').innerText === '重 置') {
        ref.current.setFieldsValue({
          beginFlightDate: moment(),
          endFlightDate: moment(),
        });
      }
      return { ...params };
    }
  }, []);
  // 选中项
  const changeRows = (selectedKeys, selectedRows) => {
    setSelectedRowKeys([...selectedKeys]);
    setSelectRow([...selectedRows])
  }
  const showAuditModal = () => {
    if (selectRow.length !== 1) {
      return message.error('请选择一条航班');
    }
    props.dispatch({
      type: 'auditDetail/resetUploadList'
    });
    // 缓存点击的航班数据
    window.localStorage.setItem('usualMonitorFlightNo',JSON.stringify(selectRow));
    // 缓存点击的航班类型 用于区别关闭赔偿单的回调地址
    window.localStorage.setItem('usualMonitorBackUrl','/usualMonitor/usualMonitor');
    router.push({
      pathname: '/usualMonitor/usualMonitor/AuditDetail',
      state: {selectRow}
    })
  }
  const columns = [
    {
      title: '航班日期',
      width: 120,
      dataIndex: 'flightDate',
      valueType: "date",
      fixed: 'left',
      hideInSearch: true
    },
    {
      title: '航班号',
      dataIndex: 'flightNumber',
      width: 90,
      fixed: 'left',
      order: 2,
      renderFormItem: (_, { defaultRender, ...rest }) => {
        return <Input 
          {...rest} 
          onChange={e => {
            e.target.value = formatFlightNo(e.target.value);
            rest.onChange(e.target.value)
          }} 
          allowClear maxLength={6} placeholder="3U" />;
      }
    },
    {
      title: '起始日期',
      hideInTable: true,
      dataIndex: 'beginFlightDate',
      order: 4,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '结束日期',
      hideInTable: true,
      dataIndex: 'endFlightDate',
      order: 3,
      renderFormItem: (_, { ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            style={{ width: '100%' }}
            format={format}
            {...rest}
          />
        );
      },
    },
    {
      title: '航线类型',
      key: 'flightType',
      hideInSearch: true,
      filters: false,
      dataIndex: 'flightType',
      width: 120,
      valueEnum: {
        '': '全部',
        'D': '国内',
        'I': '国际',
      },
    },
    {
      title: '是否取消',
      key: 'flightState',
      filters: false,
      hideInSearch: true,
      dataIndex: 'flightState',
      width: 120,
      valueEnum: {
        '': '全部',
        'D': '延误',
        'C': '取消',
      },
    },
    {
      title: '起飞航站',
      dataIndex: 'org',
      width: 130,
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder='请选择'
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {
              selectData && selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE} value={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      }
    },
    // 到达
    {
      title: '到达航站',
      dataIndex: 'dst',
      width: 100,
      renderFormItem: (_, { ...rest }, form) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder='请选择'
            defaultActiveFirstOption={false}
            showArrow={false}
            filterOption={true}
            optionFilterProp="children"
            notFoundContent={null}
            {...rest}
          >
            {
              selectData && selectData.map((v, i) => {
                return (
                  <Option key={v.CITY3CODE} value={v.CITY3CODE}>{v.CITYNAME}-{v.CITY3CODE}</Option>
                )
              })
            }
          </Select>
        );
      }
    },
    {
      title: '计划起飞时间',
      hideInSearch: true,
      dataIndex: 'std',
      width: 130
    },
    {
      title: '预计起飞时间',
      hideInSearch: true,
      dataIndex: 'etd',
      width: 130
    },
    {
      title: '实际起飞时间',
      hideInSearch: true,
      dataIndex: 'atd',
      width: 130
    },
    {
      title: '计划到达时间',
      hideInSearch: true,
      dataIndex: 'sta',
      width: 130
    },
    {
      title: '预计到达时间',
      hideInSearch: true,
      dataIndex: 'eta',
      width: 130
    },
    {
      title: '实际到达时间',
      hideInSearch: true,
      dataIndex: 'ata',
      width: 130
    },
    {
      title: '机型',
      hideInSearch: true,
      dataIndex: 'fltCode',
      width: 100
    },
    {
      title: '飞机号',
      dataIndex: 'planecode',
      order: 1,
      width: 100
    },
    {
      title: '登机门',
      hideInSearch: true,
      dataIndex: 'gate',
      width: 100
    },
    {
      title: '出港机位',
      hideInSearch: true,
      dataIndex: 'bayOutgiong',
      width: 100
    },
    {
      title: '座位布局',
      hideInSearch: true,
      dataIndex: 'seatLayout',
      width: 100
    }
    ,
    {
      title: '机组',
      hideInSearch: true,
      dataIndex: 'cabinCren',
      width: 100
    }
    ,
    {
      title: '是否有有氧舱',
      hideInSearch: true,
      dataIndex: 'hasOxygen',
      width: 130,
      valueEnum: {
        '': '全部',
        'Y': '是',
        'N': '否',
      },
    }
  ];
  return (
    <>
      <ProTable
        options={{density: false, fullScreen: true, reload:false, setting: true }}
        size='small'
        className={`${styles.oversaleTable} rest-pro-table-form-compact ${isCollapse ? '' : 'collapse'}`}
        scroll={{ x: 1000, y: height }}
        headerTitle={
          <span style={{ paddingRight: 10, fontWeight: "bold", color: "#000" }}>全部航班列表</span>
        }
        toolBarRender={() => [
          <AuthComponent authCode="usualMonitor.usualMonitor.saveOrderInfo">
            <Button type="primary" onClick={showAuditModal}>
              航延补偿
            </Button>
          </AuthComponent>
          ,
        ]}
        search={{
          onCollapse: val => {
            controlC(val);
          }
        }}
        actionRef={actionRef}
        formRef={ref}
        dateFormatter="YYYY-MM-DD"
        pagination={{
          showSizeChanger: true,
          showTotal: (total, range) => `${range[0]}-${range[1]} 共 ${total} 项`
        }}
        rowKey="id"
        beforeSearchSubmit={beforeSearchSubmit}
        request={params => {
          if (!params['beginFlightDate'] && !params['endFlightDate']) {
            params['beginFlightDate'] = moment().format('YYYY-MM-DD');
            params['endFlightDate'] = moment().format('YYYY-MM-DD');
            ref.current.setFieldsValue({
              beginFlightDate: moment()
            })
            ref.current.setFieldsValue({
              endFlightDate: moment()
            })
          }
          return queryFlightTable({ ...params });
        }}
        postData={data => {
          setSelectedRowKeys([]);
          setSelectRow([]);
          return data;
        }}
        columns={columns}
        rowSelection={{ selectedRowKeys,onChange: changeRows }}
        tableAlertRender={() => {
          return false
        }}
      />
    </>
  );
};

export default connect(state => state.auditDetail)(Form.create()(TableList));